<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\AppOffline;

class TalkController extends Controller
{
    /**
     * 聊天记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function info(Request $request)
    {
        $this->validate($request, [
            'to' => 'required|numeric',
            'time' => 'required|numeric',//本次打开窗口时间
        ]);
        $talk = AppOffline::where(function ($q) use ($request) {
                $q->where([
                    'from'=>request('to'),
                    'to'=>user_id(),
                ])->orwhere(function ($q) use ($request) {
                    $q->Where([
                        'from'=>user_id(),
                        'to'=>request('to'),
                    ]);
                });

            })
            ->where('addtime' ,'<', $request->time)
            ->orderby('addtime' , 'desc')
            ->paginate(15);
        if(!empty($talk)){
            $talk = $talk->toarray();
            $data = $talk['data'];
            $addtime = array_column($data,'addtime');
            array_multisort($addtime,SORT_ASC,$data);
            $talk['data'] = $data;
        }
        return $this->successReturn($talk);

    }

    public function list(Request $request)
    {
        $user_id = user_id();
        $talk =\DB::select("SELECT
	sum( `status` ) AS unread,
	receiver,
	`type`,
	content,
	addtime,
	m.nickname,
	m.head_image 
FROM
	(
	SELECT
		`to` AS receiver,
		`type`,
		`content`,
		`status`,
		addtime 
	FROM
		`app_offline` 
	WHERE
		( `from` = $user_id ) 
		AND ( `to` <> $user_id ) UNION
	SELECT
		`from` AS receiver,
		`type`,
		`content`,
		`status`,
		addtime 
	FROM
		`app_offline` 
	WHERE
		( `from` <> $user_id ) 
		AND ( `to` = $user_id ) 
	ORDER BY
		`addtime` DESC 
	) AS newTable
	INNER JOIN user_infos m ON receiver = m.user_id 
GROUP BY
	receiver 
ORDER BY
	addtime DESC LIMIT 30");
        return $this->successReturn($talk);
    }

}